//
//  HomePageViewController.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/8/27.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import SkeletonView
import RxSwift


/// 首页
class HomePageViewController: BaseWebViewController {
    
    let skeletonView = UIView()
    
    init() {
        super.init(url: UIDevice.current.isZhHans ? "https://ae-solar.com" : "https://www.facebook.com/aesolarenergy")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "江苏新源".localized
        
        skeletonView.config
            .backgroundColor(.white)
            .addTo(view)
            .extra{
                $0.isSkeletonable = false
        }.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        for i in 0..<6 {
            let leftView = UIView()
            leftView.config
                .cornerRadius(5)
                .masksToBounds(true)
                .addTo(skeletonView)
                .extra{
                    $0.isSkeletonable = true
            }.makeConstraints { (make) in
                make.left.equalTo(20)
                make.top.equalTo(CGFloat(i) * 120 + 20)
                make.width.height.equalTo(100)
            }
            
            UILabel().config
                .numberOfLines(0)
                .addTo(skeletonView)
                .extra{
                    $0.isSkeletonable = true
            }.makeConstraints { (make) in
                make.top.equalTo(leftView.snp.top)
                make.bottom.equalTo(leftView.snp.bottom)
                make.left.equalTo(leftView.snp.right).offset(20)
                make.right.equalTo(-20)
            }
        }
        
        webView.rx.title
            .map{ $0 ?? "" }
            .filter{ $0.count > 0 }
            .subscribe(onNext: { [weak self] (_) in
                UIView.animate(withDuration: 0.3, animations: {
                    self?.skeletonView.alpha = 0
                }) { (_) in
                    self?.skeletonView.removeFromSuperview()
                }
            }).disposed(by: rx.disposeBag)
        
        skeletonView.showAnimatedSkeleton()
    }
    
    override func navigationBarStyle() -> NavigationBarStyle {
        return .baseColor
    }
    
}

extension HomePageViewController: SkeletonTableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    func collectionSkeletonView(_ skeletonView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier {
        return HomePageCell.reuseIdentifier
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCell(HomePageCell.self)
    }
    
}

